package com.wx.mp.utils;

import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 分页插件结果转换工具类.<br/>
 *
 * Copyright: Copyright (c) 2017  zteits
 *
 * @ClassName: PageBeanUtil.java
 * @Description:
 * @version: v1.0.0
 * Modification History:
 */
public class PageBeanUtil {

    /**
     * 将PageInfo 转换成PageBean.<br/>
     *
     * @param form  PageInfo<R> 对象.<br/>
     * @param to    PageBean<L> 对象.<br/>
     * @param clazz
     */
    public static <R, L> void copyProperties(PageInfo<R> form, PageBean<L> to, Class<L> clazz) {
        List<L> list = new ArrayList<L>();
        if (CollectionUtils.isEmpty(form.getList())) {
            return;
        }
        for (R source : form.getList()) {
            if (null == source) {
                continue;
            }
            try {
                L target = clazz.newInstance();
                BeanUtils.copyProperties(source, target);
                list.add(target);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        to.setDataList(list);
        to.setPageNum(form.getPageNum());
        to.setPageSize(form.getPageSize());
        to.setPages(form.getPages());
        to.setPageTotals(Integer.valueOf(String.valueOf(form.getTotal())));
    }

}
